<template>
	<view class="container">
		<!-- 门店名 -->
		<view v-if='store != ""' class="container">
		    <!-- 门店胶囊按钮 -->
		    <view 
		      class="store-button" 
		      @click="navigateToStoreList"
		    >
		      当前门店:{{ store.name }}
		    </view>
		</view>
		<!-- 轮播图区域 -->
		<swiper class="swiper-box" :autoplay="true" :interval="3000" :duration="1000" circular>
			<swiper-item v-for="(item, index) in swiperData" :key="index" @click="toUrl(item.link)">
				<image class="swiper-img" :src="item.image" mode="aspectFill" />
			</swiper-item>
		</swiper>
		<view v-if='notice != ""'>
			<u-notice-bar :text="notice" bgColor='#f3f3f3' color='#bc927a'></u-notice-bar>
		</view>
		<view style='margin:10px;' >
			<u-search placeholder="搜索产品" v-model="keyword" :showAction='false' @search='findGoods'></u-search>
		</view>
		<!-- 小图轮播 -->
		<view v-if='banner2 && banner2.length > 0' >
			<u-swiper :list="banner2" keyName="image"  @click="toLink"></u-swiper>
		</view>
		
		<!-- 活动产品列表 -->
		<view v-if='promition && promition.length > 0'>
			<view class="section-title">限时活动</view>
			<view class="activity-list">
				<view v-for="(item, index) in promition" :key="index" class="activity-item" @click="toDetail(item.id)">
					<image class="product-img" :src="item.indexCover" mode="aspectFit"></image>
					<view class="product-info">
						<view class="product-name">{{ item.name }}</view>
						<view class="product-price">¥{{ item.price }}</view>
						<view :class="['activity-tag', item.type === '满减' ? 'reduce' : 'gift']">
							{{ item.promotionName }}
						</view>
					</view>
				</view>
			</view>
		</view>
		
		

		<!-- 推荐产品列表 -->
		<view v-if='recommends && recommends.length > 0'>
			<view class="section-title">新品推荐</view>
			<view class="recommend-list">
				<view v-for="(item, index) in recommends" :key="index" class="recommend-item">
					<view style='display: flex;justify-content: center;'>
						<image class="recommend-img" :src="item.indexCover" mode="aspectFit" @click="toDetail(item.id)"></image>
					</view>
					<view class="recommend-info">
						<view class="recommend-name">{{ item.name }}</view>
						<view class="recommend-price">¥{{ item.specifications[0].__metadata.price }}</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 后台设置的首页产品列表 -->
		<view v-if='showProducts && showProducts.length > 0'>
			<view v-for='products in showProducts'>
				<view v-if='products.images && products.images.length > 0'>
					<u-swiper :list="products.images" height='260' :autoplay='false' :indicator='true' indicatorMode='dot'></u-swiper>
				</view>
				<view v-else>
					<view v-if='products.image' >
						<img style='width:100%;margin-top:20px' :src="products.image" mode="widthFix" />
					</view>
					<view v-else class="section-title">
						{{products.title}}
					</view>
				</view>
				<view class="recommend-list">
					<view v-for="(item, index) in products.products" :key="index" class="recommend-item">
						<view style='display: flex;justify-content: center;'>
							<image class="recommend-img" :src="item.__metadata.indexCover" mode="aspectFit" @click="toDetail(item.id)"></image>
						</view>
						<view class="recommend-info">
							<view class="recommend-name">{{ item.__metadata.name }}</view>
							<view class="recommend-price">¥{{ item.__metadata.specifications[0].__metadata.price }}</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部图片集 -->
		<view v-if='buttomImages && buttomImages.length > 0' style='margin-top:20px;'>
			<view v-for='item in buttomImages'>
				<img style='width:100%;' :src="item.image" mode="widthFix" @click='toUrl(item.link)' />
				
			</view>
		</view>
		
		<!-- 客服 -->
		<view class="fixed-container">
		    <u-button icon='kefu-ermai' text="在线客服" size='small' shape='circle' :plain='true' open-type="contact"></u-button>
		  </view>
		<!-- 弹窗广告 -->
		<view v-if='popupImage != ""'>
			<u-overlay :show="showPopup">
				<view class="warp">
					<view style='display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100vh; width: 100%; position: fixed; top: 0; left: 0;'>
					    <view @click='toUrl(popupImage.link)' style='display: flex; justify-content: center; align-items: center;'>
					        <u-image :src='popupImage.image' width='703rpx' height='924rpx'></u-image>
					    </view>
					    <view style='margin-top: 10px;'>
					        <u-icon name="close-circle" size='38' @click="showPopup = false" color='#909399'></u-icon>
					    </view>
					</view>
				</view>
			</u-overlay>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				keyword: '',
				showPopup: false,
				swiperData: [],
				promition: [],
				recommends: [],
				popupImage: '',
				banner2: [],
				notice: '',
				buttomImages: [],
				showProducts: [],
				store: ''
			}
		},
		onShow() {
			
			let token = uni.getStorageSync('api_token')
			if(token != ''){
				let store = uni.getStorageSync('store')
				if(store != ''){
					this.store = store
					console.log('门店',store)
					this.getBanner()
					this.getRecommend()
					this.getPromotion()
					this.getProductShow()
				}else{
					this.getAuthorizeInfo()
				}
			}
		},
		onLoad(options) {
			let token = uni.getStorageSync('api_token')
			if (token == '') {
				let _this = this
				uni.login({
					success(result) {
						let data = {
							code: result.code,
						}
						if(typeof(options.recommendedUser) != 'undefined'){
							data.recommendedUser = options.recommendedUser
						}
						_this.request.get(`wechat/mini/login`, data).then((res) => {
							uni.setStorageSync('api_token', res.data.token)
							_this.request.get(`api/user`).then((res) => {
								uni.setStorageSync('myUser',res.data.id)
							})
							_this.getAuthorizeInfo()
						})
					}
				})
			}
		},
		onShareAppMessage(res) {
			let myUser = uni.getStorageSync('myUser')
			if(myUser != ''){
				return {
					title: '华盛咖啡',
					desc: '华盛咖啡',
					path: `/pages/index/index?recommendedUser=${myUser}`,
				}
			}
		},
		methods: {
			getBanner() {
				this.request.get('public/albums',{
					'@filter': `entity.getStore().getId() == ${this.store.id} && entity.getTitle() == 'index-banner'`
				}).then((res) => {
					this.swiperData = res.data[0].pictures
					console.log('轮播',this.swiperData)
				})
				this.request.get('public/albums',{
					'@filter': `entity.getStore().getId() == ${this.store.id} && entity.getTitle() == 'index-popup'`
				}).then((res) => {
					if(res.data[0].pictures && res.data[0].pictures.length > 0){
						this.popupImage = res.data[0].pictures[0]
						this.showPopup = true
					}
				})
				this.request.get('public/albums',{
					'@filter': `entity.getStore().getId() == ${this.store.id} && entity.getTitle() == 'index-banner2'`
				}).then((res) => {
					console.log('banner2', res.data[0])
					if(res.data[0].pictures && res.data[0].pictures.length > 0){
						this.banner2 = res.data[0].pictures
					}
				})
				this.request.get(`public/contents`,{
					'@filter': `entity.getStore().getId() == ${this.store.id} && entity.getCategory().getType().getSlug() == 'notice'`
				}).then((res) => {
					this.notice = res.data[0].content
				})
				this.request.get(`public/albums`,{
					'@filter': `entity.getStore().getId() == ${this.store.id} && entity.getTitle() == 'index-buttom-images'`
				}).then((res) => {
					this.buttomImages = res.data[0].pictures
				})
			},
			getRecommend() {
				// this.request.get(`api/products`, {
				// 	'@filter': `entity.getIsRecommended() == true && entity.getIsOnSale() == true`,
				// 	'@expands': "['specifications']"
				// }).then((res) => {
				// 	this.recommends = res.data
				// })
			},
			getProductShow(){
				this.request.get(`public/product-shows`,{
					'@filter': `entity.getEnabled() == true && entity.getStore().getId() == ${this.store.id}`,
					'@expands': "['entity.products.specifications']",
					'@order': `entity.listOrder|ASC`
				}).then((res) => {
					console.log(123,res.data)
					this.showProducts = res.data
				})
			},
			getPromotion() {
				this.request.get(`api/promotions/from-all-product`,{
					'@filter': `entity.getStartTime() < datetime.get('now') && entity.getEndTime() > datetime.get('now') && entity.getEnabled() == true`,
					'@expands': "['entity.specifications.product']"
				}).then((res) => {
					console.log('prom,',res.data)
					// this.promition = res.data
					let promotionProducts = []
					for(let i of res.data){
						if(i.specifications){
							for(let j of i.specifications){
								console.log(1)
								let product = {
									name: j.__metadata.product.__toString,
									id: j.__metadata.product.id,
									cover: j.__metadata.product.__metadata.cover,
									price: j.__metadata.price,
									promotionName: i.name
								}
								promotionProducts.push(product)
							}
						}
					}
					console.log('p',promotionProducts)
					this.promition = promotionProducts
				})
			},
			toLink(e){
				console.log(e)
				if(this.banner2[e].link){
					uni.navigateTo({
						url: this.banner2[e].link
					})
				}
			},
			toDetail(id) {
				const tmplIds = [
					'uTZLnU0Ltow5L0KwpPfQ5t1YHpnduJKlMOAyg08ntw8'
				];
				uni.requestSubscribeMessage({
					tmplIds: tmplIds,
					success: res => {
						uni.navigateTo({
							url: `/pages/product/detail?id=${id}`
						})
					}
				})
			},
			closePopup() {
				this.showPopup = false
				this.navigateTo('/pages/promotion/promotion') // 跳转到活动页面
			},
			findGoods(){
				if(this.keyword.trim() == ''){
					uni.showToast({
						title: '请输入搜索内容',
						icon: 'none'
					})
					return
				}
				uni.navigateTo({
					url: `/pages/product/search?keyword=${this.keyword}`
				})
			},
			toUrl(url){
				if(url){
					uni.navigateTo({
						url: url
					})
				}
			},
			getAuthorizeInfo(a = "scope.userLocation") { //1. uniapp弹窗弹出获取授权（地理，个人微信信息等授权信息）弹窗
				var _this = this;
				uni.authorize({
					scope: a,
					success() { //1.1 允许授权
						console.log('已经授权')
						_this.getLocationInfo();
					},
					fail() { //1.2 拒绝授权
						console.log('没有授权')
						uni.showModal({
							title: '温馨提示',
							content: '获取定位失败，为了给您提供更好的体验，请您点击右上角。。。，点击设置，微信信息设置选择允许,如有疑问请联系客服！',
							showCancel: false,
							confirmText: '我知道了',
							success: () => {
			
							}
						})
						_this.getDefaultStore()
					}
				})
			},
			getLocationInfo() { //2. 获取地理位置
				var _this = this;
				uni.getLocation({
					type: 'wgs84',
					success(res) {
						let latitude, longitude;
						latitude = res.latitude.toString();
						longitude = res.longitude.toString();
						console.log('经纬度',latitude,longitude)
						_this.getCityByLocation(latitude, longitude);
					},
					fail() {
						console.log('获取不到')
						_this.getDefaultStore()
					}
				});
			},
			//获取默认的店铺，只有在定位失败的时候运行
			getDefaultStore() {
				this.request.get("public/stores/1",{
				}).then((res) => {
					console.log('Defaultstore',res.data)
					this.store = res.data
					uni.setStorageSync('store',this.store)
					this.getBanner()
					this.getRecommend()
					this.getPromotion()
					this.getProductShow()
				})
			},
			getCityByLocation(latitude, longitude) {
			    const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=DT3BZ-BIVCT-TTFXY-VFHRR-PXXRE-MLFIS`;
			    uni.request({
			        url: url,
			        method: 'GET',
			        success: (res) => {
			            if (res.statusCode === 200) {
							console.log('地理位置',res)
			                const city = res.data.result.address_component.city; // 例如：广东省深圳市南山区科技园
			                console.log('当前城市：', city);
							// 根据城市获取对应的城市门店，如果该城市没有门店的，就获取总店
							this.request.get(`public/stores`,{
								'@filter': `entity.getRegion().getName() == "${city}"`
							}).then((res) => {
								if(res.data && res.data.length > 0){
									this.store = res.data[0]
									uni.setStorageSync('store',this.store)
									this.getBanner()
									this.getRecommend()
									this.getPromotion()
									this.getProductShow()
								}else{
									this.getDefaultStore()
								}
							})
			            } else {
			                console.error('获取城市信息失败');
			            }
			        },
			        fail: () => {
			            console.error('请求失败');
			        }
			    });
			},
			navigateToStoreList(){
				uni.navigateTo({
					url: '/pages/index/stores'
				})
			}
		}
	}
</script>

<style scoped>
	/* 胶囊样式 */
	.store-button {
	  position: absolute;
	  top: 9%;
	  transform: translateY(-50%);
	  padding: 8rpx 26rpx;
	  background-color: #909399; /* 橙色背景 */
	  color: #fff;
	  border-radius: 0px 32rpx 32rpx 0px;
	  font-size: 32rpx;
	  z-index: 999;
	  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);
	}
	.container {
		padding-bottom: 30rpx;
	}

	.swiper-box {
		height: 66.67vh;
	}

	.swiper-img {
		width: 100%;
		height: 100%;
	}

	.section-title {
		font-size: 36rpx;
		font-weight: bold;
		padding: 20rpx 30rpx;
	}

	.activity-item {
		display: flex;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #eee;
	}

	.product-img {
		width: 200rpx;
		height: 200rpx;
		border-radius: 10rpx;
	}

	.product-info {
		flex: 1;
		margin-left: 20rpx;
	}

	.product-name {
		font-size: 32rpx;
		color: #333;
	}

	.product-price {
		font-size: 28rpx;
		color: #e4393c;
		margin-top: 10rpx;
	}

	.activity-tag {
		display: inline-block;
		padding: 6rpx 12rpx;
		border-radius: 6rpx;
		font-size: 24rpx;
		margin-top: 10rpx;
	}

	.reduce {
		background-color: #ffe5e5;
		color: #e4393c;
	}

	.gift {
		background-color: #e5ffeb;
		color: #00c853;
	}

	.recommend-list {
		display: flex;
		flex-wrap: wrap;
		padding: 0 15rpx;
	}

	.recommend-item {
		width: 42%;
		margin: 15px 4%;
		background: #fff;
		border-radius: 10rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		padding: 10px 0px;
	}

	.recommend-img {
		width: 260rpx;
		height: 260rpx;
		border-radius: 20rpx;
	}

	.recommend-info {
		padding: 20rpx;
	}

	.recommend-name {
		font-size: 28rpx;
		font-weight: bold;
	}

	.recommend-price {
		font-size: 26rpx;
		color: #e4393c;
		margin-top: 10rpx;
	}

	.popup-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
	}

	.popup-img {
		width: 80%;
		border-radius: 20rpx;
	}
	
	.fixed-container {
  position: fixed; /* 固定定位 */
  left: 10px;     /* 距离左边10px */
  bottom: 10px;   /* 距离底部10px */
  z-index: 1000;  /* 确保按钮在其他内容上方 */
}
</style>